package com.jotta.client.communicate;


import com.jotta.client.R;
import com.jotta.client.utility.Utility;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class JottaPath {

    static private String PATH_BASE = Configuration.INITIAL_SERVER_PATH;
    static private String SLASH = Configuration.SLASH;

    private String username;
    private ArrayList<String> pathList = new ArrayList<String>();


    public JottaPath(String username) {
        this.username = username;
    }

    public JottaPath(String username, String path) {
        this.username = username;
        addPath(path);
    }

    public void goHome() {
        pathList.clear();
    }

    private void addPath(String newPath) {
        String[] paths = newPath.split(SLASH);
        if (paths.length > 0) {
            List<String> tempList = Arrays.asList(paths);
            if (tempList.get(0).trim().length() == 0) {
                tempList = tempList.subList(1, tempList.size());
            }
            pathList.addAll(tempList);
        } else {
            pathList.add(newPath);
        }
    }

    public JottaPath goForward(String folderName) {
        addPath(folderName);
        return this;
    }

    public JottaPath goBackward() {
        if (pathList.size() > 0) {
            if (currentIsArchive()) {
                goHome();
            } else {
                pathList.remove(pathList.size() - 1);
            }
        }
        return this;
    }

    public int getCurrentPathLevels() {
        return this.pathList.size();
    }

    public String getCurrentFolderName() {
        if (pathList.size() > 0) {
            return pathList.get(pathList.size() - 1);
        } else {
            return Configuration.getRes().getString(R.string.home_menu);
        }
    }

    public String getBaseUrl() {
        return PATH_BASE + this.username;
    }

    public boolean currentIsArchive() {
        String apath = PATH_BASE + username + Configuration.JOTTA_ARCHIVE_PATH + SLASH;
        String cpath = getFullPathUnencoded();
        return cpath.equalsIgnoreCase(apath);
    }

    private String getFullPath(boolean encoded) {
        StringBuilder sb = new StringBuilder(PATH_BASE);
        sb.append(username).append(SLASH);
        for (String folderName : pathList) {
            if (encoded) {
                sb.append(Utility.encodeFolderName(folderName));
            } else {
                sb.append(folderName);
            }
            sb.append(SLASH);
        }
        return sb.toString();
    }

    public String getFullPathUnencoded() {
        return getFullPath(false);
    }

    public String getFullPathEncoded() {
        return getFullPath(true);
    }


    @Override
    public String toString() {
        return getFullPath(false);
    }

}
